﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.IO;

namespace Store.Web.PushNotifications
{
    public class PushNotificationsHelper
    {
        public static PushNotificationResult SendToastNotification(ToastNotification toastNotification, string url)
        {
            PushNotificationResult result = new PushNotificationResult();

            try
            {
                string xml = toastNotification.GetXml();
                byte[] notification = Encoding.Default.GetBytes(xml);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";

                request.ContentLength = notification.Length;
                request.ContentType = "text/xml";

                request.Headers.Add("X-WindowsPhone-Target", "toast");
                request.Headers.Add("X-NotificationClass", "2");

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(notification, 0, notification.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                
                result.NotificationStatus = response.Headers["X-NotificationStatus"];
                result.SubscriptionStatus = response.Headers["X-SubscriptionStatus"];
                result.DeviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
            }
            catch (Exception e)
            {
                result.Error = e;
            }

            return result;
        }
    }
}